<template>
  <view class="add-product-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          placeholder="请输入商品名称或编码" 
          v-model="searchKeyword"
          @input="handleSearch"
        />
        <view class="clear-btn" v-if="searchKeyword" @click="clearSearch">
          <uni-icons type="clear" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <scroll-view
      class="product-scroll" 
      scroll-y
      lower-threshold="50"
      enable-back-to-top
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMoreProducts"
      :scroll-top="scrollTop"
      @scroll="onScroll"
    >
       <!-- 加载状态 -->
        <view class="loading-state" v-if="loading && productList.length === 0">
          <text class="loading-text">正在加载商品数据...</text>
        </view>
        
        <view class="product-list" v-if="!loading || productList.length > 0">
          <!-- 商品卡片 -->
          <view
            class="product-card" 
            v-for="(product, index) in productList" 
            :key="product.rowid"
            @click="goToProductDetail(product)"
          >
      
            <!-- 商品图片 -->
            <view class="product-image">
              <image 
                :src="getFirstImage(product['6864930a4e2949f411990010'])" 
                mode="aspectFill"
                class="image"
              ></image>
              <!-- 查看批次按钮 -->
              <text class="view-batch-text" @click.stop="goToBatchView(product)">查看批次</text>
              
            </view>
            
            <!-- 描述区域 -->
            <view class="product-info">
              <text class="product-name">{{ product['68634c1c87058ae1c65da306'] }}</text>
              <text class="product-code">商品条码：{{ product['68634c1c87058ae1c65da312'] }}</text>
               <text class="product-code">供应商：{{ product['68b4fa66153a1d736d8571c1'] }}</text>
            </view>
            
          </view>
          
          <!-- 空状态 -->
          <view class="empty-state" v-if="productList.length === 0 && !loading">
            <text class="empty-text">暂无商品数据</text>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="load-more" v-if="productList.length > 0">
            <text class="load-more-text" v-if="loadingMore">正在加载更多...</text>
            <text class="load-more-text" v-else-if="noMoreData">没有更多数据了</text>
            <text class="load-more-text" v-else-if="loadMoreError" @click="loadMoreProducts">加载失败，点击重试</text>
          </view>
        </view>
    </scroll-view>
    
    <!-- 底部确定按钮 -->
    <view class="bottom-actions">
      <button 
        class="confirm-btn" 
        @click="handleConfirm"
      >
        新建商品
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import http from '../../../utils/request'
import { callWorkflowListAPI, callWorkflowAPI, callWorkflowListAPIPaged } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import { useTaskStore } from '../../../store/task'


const userStore = useUserStore()
const taskStore = useTaskStore()

// 搜索关键词
const searchKeyword = ref('')

// 商品列表数据
const productList = ref([])

// 加载状态
const loading = ref(false)
const loadingMore = ref(false)
const noMoreData = ref(false)
const loadMoreError = ref(false)
const refreshing = ref(false)

// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 滚动位置
const scrollTop = ref(0)

// 滚动事件处理 - 使用防抖避免频繁更新
let scrollTimer = null
const onScroll = (e) => {
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }
  scrollTimer = setTimeout(() => {
    scrollTop.value = e.detail.scrollTop
  }, 100)
}


// 新建商品
const handleConfirm = () => {
  uni.navigateTo({
    url: '/pages/warehouse/product/add-product'
  })
}

// 处理搜索
const handleSearch = () => {
  // 搜索时重置数据并重新加载
  resetData()
  getProductData(false, true)
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 加载更多商品 - 独立的加载更多方法
const loadMoreProducts = () => {
  console.log('加载更多商品');
  if (loadingMore.value || noMoreData.value || loadMoreError.value) {
    return
  }
  
  // 添加防抖处理，避免频繁触发
  setTimeout(() => {
    loadMoreProductData()
  }, 300)
}

// 独立的加载更多数据方法
const loadMoreProductData = async () => {
  try {
    loadingMore.value = true
    loadMoreError.value = false
    
    // 获取用户所属供应商rowid数组
    const supplierField = userStore.getUserInfo()['68ea18b6470b6cef2f580870']
    if (!supplierField) {
      console.error('用户信息中缺少供应商字段')
      uni.showToast({
        title: '用户供应商信息缺失',
        icon: 'none'
      })
      loadMoreError.value = true
      return
    }
    const userSupplierRowids = JSON.parse(supplierField)
    
    let currentPage = pageNum.value + 1
    let newFilteredData = []
    let hasMoreData = true
    
    // 循环加载数据直到有符合条件的商品或没有更多数据
    while (newFilteredData.length === 0 && hasMoreData) {
      console.log(`正在加载第${currentPage}页数据...`)
      
      const result = await callWorkflowListAPIPaged('68634c1c87058ae1c65da305', [], pageSize.value, currentPage, 0)
      
      if (result && result.data) {
        console.log(`第${currentPage}页商品数据:`, result.data)
        
        // 过滤符合用户所属供应商的商品
        const filteredData = filterProductsBySupplier(result.data, userSupplierRowids)
        
        console.log(`第${currentPage}页过滤后的商品数据:`, filteredData)
        
        // 将过滤后的数据添加到结果中
        newFilteredData = [...newFilteredData, ...filteredData]
        
        // 检查是否还有更多数据
        if (result.data.length < pageSize.value || currentPage * pageSize.value >= (result.total || 0)) {
          hasMoreData = false
          noMoreData.value = true
        } else {
          currentPage++
        }
        
        // 如果已经有符合条件的数据了，停止循环
        if (newFilteredData.length > 0) {
          break
        }
      } else {
        hasMoreData = false
        loadMoreError.value = true
      }
    }
    
    // 追加数据到现有列表
    if (newFilteredData.length > 0) {
      productList.value = [...productList.value, ...newFilteredData]
      pageNum.value = currentPage // 更新页码为最后加载的页码
    }
    
  } catch (error) {
    console.error('加载更多商品数据失败:', error)
    loadMoreError.value = true
  } finally {
    loadingMore.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  pageNum.value = 1
  noMoreData.value = false
  loadMoreError.value = false
  scrollTop.value = 0 // 刷新时重置滚动位置
  getProductData(true)
}

// 重置数据
const resetData = () => {
  productList.value = []
  pageNum.value = 1
  totalCount.value = 0
  noMoreData.value = false
  loadMoreError.value = false
  scrollTop.value = 0 // 重置滚动位置
}



const getFirstImage = (imageData) => {
  if (!imageData) return ''
  
  try {
    // 如果已经是字符串数组，直接返回第一个
    if (Array.isArray(imageData)) {
      return imageData[0] || ''
    }
    
    // 如果是JSON字符串，解析后取第一个图片的thumbnail_full_path
    const parsedData = JSON.parse(imageData)
    if (Array.isArray(parsedData) && parsedData.length > 0) {
      return parsedData[0].thumbnail_full_path || parsedData[0].file_path || ''
    }
  } catch (error) {
    console.error('解析图片数据失败:', error)
  }
  
  return ''
}

// 过滤商品供应商的辅助函数
const filterProductsBySupplier = (products, userSupplierRowids) => {
  return products.filter(product => {
    try {
      // 获取商品的供应商rowid
      const supplierField = product['6865ee3d57603df8e65ce609']
      if (!supplierField) {
        console.log('商品缺少供应商字段')
        return false
      }
      
      // 第一层解析
      const parsedField = JSON.parse(supplierField)
      if (!Array.isArray(parsedField) || parsedField.length === 0) {
        console.log('供应商字段解析后不是数组或为空数组:', parsedField)
        return false
      }
      
      // 获取第一个元素
      const firstItem = parsedField[0]
      if (!firstItem || !firstItem.sourcevalue) {
        console.log('供应商字段第一个元素或sourcevalue不存在:', firstItem)
        return false
      }
      
      // 第二层解析获取rowid
      const sourceValue = JSON.parse(firstItem.sourcevalue)
      if (!sourceValue || !sourceValue.rowid) {
        console.log('sourcevalue解析后没有rowid:', sourceValue)
        return false
      }
      
      const supplierRowid = sourceValue.rowid
      console.log('商品供应商rowid:', supplierRowid)
      
      // 检查商品供应商是否在用户所属供应商数组中
      return userSupplierRowids.includes(supplierRowid)
    } catch (error) {
      console.error('解析商品供应商数据失败:', error)
      return false
    }
  })
}

// 获取商品数据 - 专注于初始加载和刷新
const getProductData = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      refreshing.value = true
    } else {
      loading.value = true
    }
    
    // 获取用户所属供应商rowid数组
    const supplierField = userStore.getUserInfo()['68ea18b6470b6cef2f580870']
    if (!supplierField) {
      console.error('用户信息中缺少供应商字段')
      uni.showToast({
        title: '用户供应商信息缺失，请联系管理员',
        icon: 'none'
      })
      loading.value = false
      refreshing.value = false
      return
    }
    const userSupplierRowids = JSON.parse(supplierField)
    console.log('用户所属供应商rowid数组:', userSupplierRowids)
    
    let currentPage = 1
    let allFilteredData = []
    let totalRecords = 0
    let hasMoreData = true
    
    // 循环加载数据直到有符合条件的商品或没有更多数据
    while (allFilteredData.length === 0 && hasMoreData) {
      console.log(`正在加载第${currentPage}页数据...`)
      
      const result = await callWorkflowListAPIPaged('68634c1c87058ae1c65da305', [], pageSize.value, currentPage, 0)
      
      if (result && result.data) {
        console.log(`第${currentPage}页商品数据:`, result.data)
        totalRecords = result.total || 0
        
        // 过滤符合用户所属供应商的商品
        const filteredData = filterProductsBySupplier(result.data, userSupplierRowids)
        
        console.log(`第${currentPage}页过滤后的商品数据:`, filteredData)
        
        // 将过滤后的数据添加到结果中
        allFilteredData = [...allFilteredData, ...filteredData]
        
        // 检查是否还有更多数据
        if (result.data.length < pageSize.value || currentPage * pageSize.value >= totalRecords) {
          hasMoreData = false
          noMoreData.value = true
        } else {
          currentPage++
        }
        
        // 如果已经有符合条件的数据了，停止循环
        if (allFilteredData.length > 0) {
          break
        }
      } else {
        hasMoreData = false
        uni.showToast({
          title: '获取商品数据失败',
          icon: 'none'
        })
      }
    }
    
    console.log('最终过滤后的商品数据:', allFilteredData)
    
    // 设置数据
    productList.value = allFilteredData
    totalCount.value = allFilteredData.length
    pageNum.value = currentPage // 记录当前已加载到的页码
    
    if (allFilteredData.length === 0 && !hasMoreData) {
      uni.showToast({
        title: '暂无符合条件的商品',
        icon: 'none'
      })
    }
    
  } catch (error) {
    console.error('获取商品数据失败:', error)
    uni.showToast({
      title: '获取商品数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 跳转到商品详情页
const goToProductDetail = (product) => {
  // 保存当前滚动位置
  uni.setStorageSync('productListScrollTop', scrollTop.value)
  uni.navigateTo({
    url: `/pages/warehouse/product/detail?rowid=${product.rowid}`
  })
}

// 跳转到批次查看页面
const goToBatchView = (product) => {
  uni.navigateTo({
    url: `/pages/warehouse/product/batch?rowid=${product.rowid}`
  })
}

watch(() => taskStore.pendingTaskUpdate, (newVal) => {
  if (newVal) {
    resetData()
    getProductData()
    // 清除待更新任务
    taskStore.clearPendingTaskUpdate()
  }
})

onLoad(async () => {
  // 页面加载时可以从服务器获取商品数据
  resetData()
  await getProductData()
})

onShow(() => {
  // 恢复滚动位置
  const savedScrollTop = uni.getStorageSync('productListScrollTop')
  if (savedScrollTop) {
    scrollTop.value = savedScrollTop
    uni.removeStorageSync('productListScrollTop')
  }
})



</script>

<style lang="scss" scoped>
.add-product-container {
  position: relative;
  height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden;
  
  .search-bar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    z-index: 10;
    height: 100rpx;
    box-sizing: border-box;
    
    .search-input-wrapper {
      display: flex;
      align-items: center;
      background-color: #f8f8f8;
      border-radius: 32rpx;
      padding: 20rpx 30rpx;
      
      .search-input {
        flex: 1;
        margin-left: 20rpx;
        font-size: 28rpx;
        color: #333333;
        
        &::placeholder {
          color: #999999;
        }
      }
      
      .clear-btn {
        margin-left: 20rpx;
        padding: 10rpx;
      }
    }
  }
  
  .product-scroll {
    position: absolute;
    top: 100rpx; /* 搜索栏高度 */
    bottom: 120rpx; /* 底部按钮高度 */
    left: 0;
    right: 0;
    background-color: #f5f5f5;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* 优化iOS滚动体验 */
    
    /* 滚动条样式优化 */
    &::-webkit-scrollbar {
      width: 6rpx;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3rpx;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3rpx;
    }
    
    &::-webkit-scrollbar-thumb:hover {
      background: #a8a8a8;
    }
    
    .loading-state {
      padding: 100rpx 0;
      text-align: center;
      
      .loading-text {
        color: #999999;
        font-size: 28rpx;
      }
    }
    
    .product-list {
      padding: 20rpx 30rpx 180rpx;
      
      .product-card {
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
        
    
        .product-image {
          width: 120rpx;
          height: 120rpx;
          margin-right: 30rpx;
          flex-shrink: 0;
          position: relative;
          
          .image {
            width: 100%;
            height: 84rpx; /* 固定高度，避免图片加载导致的抖动 */
            border-radius: 12rpx;
            object-fit: cover;
            background-color: #f0f0f0; /* 占位背景色 */
          }

          .view-batch-text{
            margin-top: 10rpx;
               font-size: 24rpx;
            color: #16dfce;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
        
        }
        
        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          
          .product-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 12rpx;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .product-code {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .product-spec {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
          }
          
          .unavailable-stock {
            font-size: 24rpx;
            color: #ff4757;
            margin-bottom: 8rpx;
          }
          
          .available-stock {
            font-size: 24rpx;
            color: #2ed573;
          }
        }
      }
      
      .empty-state {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999999;
          font-size: 28rpx;
        }
      }
      
      .load-more {
        padding: 30rpx 0;
        text-align: center;
        
        .load-more-text {
          color: #999999;
          font-size: 26rpx;
        }
      }
    }
  }
  
  .bottom-actions {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 30rpx;
    border-top: 1rpx solid #f0f0f0;
    z-index: 100;
    height: 120rpx;
    box-sizing: border-box;
    
    .confirm-btn {
      width: 100%;
      background: linear-gradient(to right, #48eceb, #0fcee9);
      color: #ffffff;
      border: none;
      border-radius: 32rpx;
      font-size: 32rpx;
      font-weight: bold;
      height: 88rpx;
      
      &.confirm-btn-disabled {
        background: #cccccc !important;
        color: #999999 !important;
        cursor: not-allowed;
        opacity: 0.6;
      }
    }
  }
}
</style>